
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>


BLEServer *pServer = NULL;
BLECharacteristic * pTxCharacteristic;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint8_t txValue = 0;
unsigned long interval = 1200; // 默认为 2 秒慢闪
unsigned long lastMillis = 0;  // 用于记录时间
#define SERVICE_UUID           "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // 服务UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" // 接收特征码
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" // 发送特征码
TaskHandle_t ledTaskHandle = NULL;
//服务监听
class MyServerCallbacks: public BLEServerCallbacks {
    //当连接成功
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
      interval = 300;
    };
    //当连接断开
    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
      interval = 2000;
    }
};

//信息监听
class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      //保存接收到的数据
      std::string rxValue = pCharacteristic->getValue();
      //如果接收的数据大于 0
      if (rxValue.length() > 0) {
        pTxCharacteristic->setValue((uint8_t*)rxValue.c_str(), rxValue.length());
        pTxCharacteristic->notify();
      }
    }
};

// LED 闪烁任务
void ledTask(void *pvParameters) {
  pinMode(48, OUTPUT);
  while (true) {
    // 动态读取当前 interval（防止任务卡住旧值）
    unsigned long currentInterval = interval;
    digitalWrite(48, LOW);
    vTaskDelay(currentInterval / 2 / portTICK_PERIOD_MS);

    digitalWrite(48, HIGH);
    vTaskDelay(currentInterval / 2 / portTICK_PERIOD_MS);
  }
}

void setup() {
  // 创建蓝牙设备，名称为LCKFB
  BLEDevice::init("yinluan");
  BLEDevice::setMTU(240);
  // 创建蓝牙服务器
  pServer = BLEDevice::createServer();
  // 设置监听
  pServer->setCallbacks(new MyServerCallbacks());
  // Create the BLE Service
  //设置蓝牙服务UUID
  BLEService *pService = pServer->createService(SERVICE_UUID);
  // 设置发送特征码
  pTxCharacteristic = pService->createCharacteristic(
                    CHARACTERISTIC_UUID_TX,
                    BLECharacteristic::PROPERTY_NOTIFY
                  );
  // 设置描述符
  pTxCharacteristic->addDescriptor(new BLE2902());

  // 设置接收特征码
  BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID_RX,
                      BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR
                    );
  pRxCharacteristic->addDescriptor(new BLE2902());
  //设置信息监听
  pRxCharacteristic->setCallbacks(new MyCallbacks());
  // 启动服务器
  pService->start();

  BLEAdvertising *pAdvertising =  pServer->getAdvertising();
  // 设置广播周期：160 * 0.625ms = 100ms
  pAdvertising->setMinInterval(160);
  pAdvertising->setMaxInterval(160);
  // 开启广播
  pAdvertising->start();

  // 创建 LED 控制任务
  xTaskCreatePinnedToCore(
    ledTask,          // 任务函数
    "LED Task",       // 名称
    1000,             // 栈大小
    NULL,             // 参数
    1,                // 优先级
    &ledTaskHandle,   // 任务句柄
    1                 // 运行在 Core 1（通常推荐给非通信任务）
  );
}

void loop() {
  if (!deviceConnected && oldDeviceConnected) {
      // 设备断开后稍微延时，恢复广播
      delay(500);
      pServer->getAdvertising()->start(); //重新启动广播
      oldDeviceConnected = deviceConnected;
  }
  // 处理设备连接后的状态
  if (deviceConnected && !oldDeviceConnected) {
      // 当设备从未连接变为连接时，更新状态
      oldDeviceConnected = deviceConnected;
  }
}